import pandas as pd
import re
import pprint


def array_split(arr, sep):
    res = []
    temp = []
    for val in arr:
        if val == sep:
            res.append(temp)
            temp = []
        else:
            temp.append(val)
    res.append(temp)
    return res


def process_segment(segment):
    processed_lines = [line.split("] ")[1].strip() for line in segment if "] " in line]

    split_line = "---"

    header = processed_lines[0]
    data = processed_lines[2:]

    # 解析数据部分
    header_row = re.split(r"\s{2,}", header.strip())
    header_row = header_row[:-1] + header_row[-1].split()
    data_rows = [
        re.split(r"\s{2,}", line.strip(), maxsplit=len(header_row) - 1)
        for line in data
        if not line.startswith(split_line)
    ]
    total_rows = data_rows[-6:]
    data_rows = data_rows[:-6]

    for row in total_rows:
        row.extend([""] * (len(header_row) - len(row)))

    # 创建 DataFrame
    df = pd.DataFrame(data_rows, columns=header_row)
    df_total = pd.DataFrame(total_rows, columns=header_row)

    df = pd.concat([df, df_total], ignore_index=True)

    return df


# 读取日志文件
with open("data.log", "r") as file:
    lines = file.readlines()

segments = array_split(lines, "\n")

dfs = [process_segment(segment) for segment in segments if segment]

# 获取所有唯一函数名
unique_functions = sorted(
    set(
        item
        for df in dfs
        for item in df["InterPreter && GC && C++ Builtin Function"]
        if item not in [""]
    )
)

# 创建初始的 DataFrame 并保持顺序
combined_df = pd.DataFrame(
    {"InterPreter && GC && C++ Builtin Function": unique_functions}
)

for i, df in enumerate(dfs):
    df.columns = [
        f"{col}_{i}" if col != "InterPreter && GC && C++ Builtin Function" else col
        for col in df.columns
    ]
    combined_df = combined_df.merge(
        df, on="InterPreter && GC && C++ Builtin Function", how="left"
    )

# 计算每行的 Time(ns) 平均值，并四舍五入保留0位小数
time_columns = [col for col in combined_df.columns if col.startswith("Time(ns)")]

# 计算平均值时只考虑数值列，并忽略空值
combined_df["Average Time(ns)"] = (
    combined_df[time_columns]
    .apply(pd.to_numeric, errors="coerce")
    .mean(axis=1, skipna=True)
    .round(0)
    .astype(int)
)

# 分离 total 行和非 total 行
total_rows = [
    "Interpreter Total Time(ns)",
    "BuiltinsApi Total Time(ns)",
    "AbstractOperation Total Time(ns)",
    "Memory Total Time(ns)",
    "Runtime Total Time(ns)",
    "Total Time(ns)",
]

total_data = combined_df[
    combined_df["InterPreter && GC && C++ Builtin Function"].isin(total_rows)
]
non_total_data = combined_df[
    ~combined_df["InterPreter && GC && C++ Builtin Function"].isin(total_rows)
]

# 对非 total 行按平均值降序排序
non_total_data = non_total_data.sort_values(by="Average Time(ns)", ascending=False)

# 合并排序后的非 total 行和 total 行
final_df = pd.concat([non_total_data, total_data], ignore_index=True)

pprint.pprint(final_df, width=1000)

excel_file = "data.xlsx"
with pd.ExcelWriter(excel_file) as writer:
    final_df.to_excel(writer, sheet_name="Runtime Stats", index=False)
